package com.syf.kit.soa.core.send.protocol;

import com.syf.kit.soa.core.SyfRpcMsg;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * TCP响应的协调器.
 */
public class TcpResponseCoordinator {
    private static final TcpResponseCoordinator INSTANCE = new TcpResponseCoordinator();

    private final Map<Long, TcpResponseLatch> latchMap;

    private TcpResponseCoordinator() {
        this.latchMap = new ConcurrentHashMap<>();
    }

    /**
     * 获取协调器单例实例
     */
    public static TcpResponseCoordinator getInstance() {
        return INSTANCE;
    }

    /**
     * 登记发送同步器
     */
    public TcpResponseLatch<SyfRpcMsg> loadSendLatch(Long requestUUID) {
        TcpResponseLatch<SyfRpcMsg> sendLatch = new TcpResponseLatch<>(requestUUID);
        latchMap.put(requestUUID, sendLatch);
        return sendLatch;
    }

    /**
     * 响应
     * */
    public void onResponse(SyfRpcMsg resp){
        TcpResponseLatch sendLatch = latchMap.get(resp.getReqUUID());
        if (sendLatch != null){
            sendLatch.attachResponse(resp);
        }
    }

    /**
     * 注销发送同步器
     * */
    protected void deregisterSendLatch(Long requestUUID){
        latchMap.remove(requestUUID);
    }
}
